<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>不刷新奖池抽奖</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
</head>

<body class="bg-gray-100 min-h-screen flex flex-col items-center justify-center">
    <div class="bg-white p-8 rounded shadow-md w-full max-w-md">
        <h1 class="text-2xl font-bold text-center mb-4">抽奖活动</h1>
        <button onclick="startLottery()"
            class="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded w-full">开始抽奖</button>
        <div id="result" class="mt-4 text-center"></div>
    </div>
    <script>
        const prizeList = [
            { name: '一等奖', probability: 0.00006, prize: '价值50万元汽车', count: 1 },
            { name: '二等奖', probability: 0.0003, prize: '20,000元现金', count: 5 },
            { name: '三等奖', probability: 0.0012, prize: '5,000元现金', count: 20 },
            { name: '四等奖', probability: 0.0029, prize: '1,000元现金', count: 50 },
            { name: '五等奖', probability: 0.0118, prize: '500元电子购物卡', count: 200 },
            { name: '六等奖', probability: 0.0294, prize: '200元话费充值', count: 500 },
            { name: '七等奖', probability: 0.1176, prize: '50元红包(微信/支付宝)', count: 2000 },
            { name: '阳光普照奖', probability: 0.83674, prize: '25元代金券', count: 14224 }
        ];

        function startLottery() {
            const availablePrizes = prizeList.filter(prize => prize.count > 0);
            if (availablePrizes.length === 0) {
                document.getElementById('result').innerHTML = '很遗憾，奖池已空，抽奖结束。';
                return;
            }

            const totalProbability = availablePrizes.reduce((acc, cur) => acc + cur.probability, 0);
            const randomNumber = Math.random() * totalProbability;
            console.log(randomNumber);

            let cumulativeProbability = 0, index = 0;
            for (const prize of availablePrizes) {
                console.log(prize);
                cumulativeProbability += prize.probability;
                console.log(cumulativeProbability);
                if (randomNumber < cumulativeProbability) {
                    prize.count--;
                    // 获取当前奖品的索引
                    index = prizeList.findIndex(item => item.name == prize.name);

                    document.getElementById('result').innerHTML = `恭喜您中了${prize.name}，奖品是：${prize.prize}`;
                    break;
                }
            }
            console.log(index);

            console.log(prizeList);

        }
    </script>
</body>

</html>